<?php
/*
 * @Created by: wangchengcheng
 * @Author: wangchengcheng
 * @Date: 2020-01-07 15:34:23
 * @LastEditors  : wangchengcheng
 * @LastEditTime : 2020-01-07 21:24:22
 */

namespace App\Console\Commands\Wblog;

use Illuminate\Console\Command;
use App\Models\Article;
use App\Models\Category;
use App\Models\Tag;
use App\Models\Nav;
use DateTime;
use File;

class GenerateSitemap extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wblog:generateSitemap';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generating the sitemap';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $articles = Article::select('id', 'updated_at')
            ->latest('updated_at')
            ->get();

        $categories = Category::select('id', 'updated_at')
            ->latest('updated_at')
            ->get();

        $tags = Tag::select('id', 'updated_at')
            ->latest('updated_at')
            ->get();

        $navs = Nav::select('id', 'updated_at')
            ->latest('updated_at')
            ->get();

        $url = '';
        foreach($articles as $article){
            $url .= $this->generateUrl(url('article', $article->id), $article->updated_at->format(Datetime::ATOM));
        }

        foreach($categories as $category){
            $url .= $this->generateUrl(url('category', $category->id), $category->updated_at->format(Datetime::ATOM));
        }

        foreach ($tags as $tag) {
            $url .= $this->generateUrl(url('tag', $tag->id), $tag->updated_at->format(DateTime::ATOM));
        }

        foreach ($navs as $nav) {
            $url .= $this->generateUrl(url('nav', $nav->id), $nav->updated_at->format(DateTime::ATOM));
        }
        $url = rtrim($url);
        $xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
$url
</urlset>
XML;
        File::put(public_path('sitemap.xml'), $xml);

        $this->info('Generating the sitemap completed.');
        $this->info('Path:' . public_path('sitemap.xml'));
    }

    public function generateUrl($loc, $lastmod)
    {
        return <<<XML
    <url>
        <loc>$loc</loc>
        <lastmod>$lastmod</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
XML;
    }
}
